# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:张广勤
@Web site: https://www.tunan.wang
@Github:www.github.com
 
@File:province_counts1_0.py
@Time:2024/5/10 8:08

@Motto:不积跬步无以至千里，不积小流无以成江海！
"""
import os
import csv
import matplotlib.pyplot as plt
import streamlit as st

def provinces_counts():
    # 定义所有省级行政区名称列表（这里只是示例，你需要补充完整的列表）
    provinces = [
        "北京", "天津", "上海", "重庆",
        "河北", "山西", "辽宁", "吉林", "黑龙江",
        "江苏", "浙江", "安徽", "福建", "江西",
        "山东", "河南", "湖北", "湖南", "广东",
        "海南", "四川", "贵州", "云南", "陕西",
        "甘肃", "青海", "台湾", "内蒙古", "广西",
        "西藏", "宁夏", "新疆", "香港", "澳门"
    ]


    # 初始化一个字典来存储每个省级行政区出现的次数
    province_counts = {province: 0 for province in provinces}

    # 替换为你的文件夹路径
    folder_path = './news'

    # 遍历文件夹下的所有文件
    for filename in os.listdir(folder_path):
        if filename.endswith('.csv'):  # 检查是否为CSV文件
            file_path = os.path.join(folder_path, filename)

            # 尝试打开文件并读取内容
            try:
                with open(file_path, 'r', encoding='utf-8', newline='') as csvfile:
                    reader = csv.reader(csvfile)

                    # 遍历CSV文件的每一行
                    for row in reader:
                        # 遍历行中的每个单元格
                        for cell in row:
                            # 检查单元格内容是否包含省级行政区名称（忽略大小写）
                            for province in provinces:
                                if province.lower() in str(cell).lower():
                                    province_counts[province] += 1
            except Exception as e:
                print(f"Error reading {file_path}: {e}")

    # 提取直方图需要的数据
    x = list(province_counts.keys())
    y = list(province_counts.values())

    # 创建直方图（实际上这里更合适的是条形图）
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 使用SimHei字体显示中文
    plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
    plt.figure(figsize=(15, 10))  # 设置图形大小
    plt.bar(x, y)  # 创建条形图
    plt.title('Province Occurrences in CSV Files')  # 设置标题
    plt.xlabel('Provinces')  # 设置x轴标签
    plt.ylabel('Occurrences')  # 设置y轴标签
    plt.xticks(rotation=45)  # 设置x轴刻度标签旋转角度以适应长标签
    plt.tight_layout()  # 自动调整子图参数，使之填充整个图像区域
    # plt.show()  # 显示图形
    return plt
    # st.pyplot(plt)